<template>
    <div class="loan-index">
        <!-- money-amount -->
        <div class="loan-out-index-wrapper have-footer wrapper" ref='content'>
            <div class="loan-out-index-box">
                <!-- <div class="money-amount" @click='goRouter("user-loan-out-detail")'>
                    <div class="money-amount-header loan-out">
                        <div class="money-amount-header__left">
                            <p class="font-headline">{{ main.lendWaiteReceiveAmount | toYuan }}</p>
                            <p class="font-caption">我的待收(元)</p>
                        </div>
                        <div class='money-amount-header__right' 
                            v-if='main.lendOverdueAmount > 0'><img src="../images/yuqi.png"><p>有逾期</p></div>
                        <div class="chat" v-if='userInfo.user' @click.stop='goChat(userInfo.user.uuid)'>
                            <img src="../images/chat_new@3x.png">
                        </div>
                    </div>
                </div> -->

                <div class="banner-box" @click='goRouter("user-loan-in-detail")'>
                    <slide
                        swiperId='banner'
                        :loop='false'
                        :autoplay='3000'>
                        <div class='banner__item'>
                            <img src="../images/banner.png">
                        </div>
                    </slide>
                    <div class="chat" v-if='userInfo.user' @click.stop='goChat(userInfo.user.uuid)'>
                        <!-- <img src="../images/chat_new@3x.png"> -->
                    </div>
                </div>

                
                <!-- message -->
                <div class="message borrow" v-if='messageList.length && messageShow' @click='goMessageDetail'>
                    <slide
                        swiperId='message'
                        direction='vertical'
                        :autoplay='2000'>
                        <div class="message__item" v-for='(item,index) in messageList' :data-index='index' :data-id='item.messageId'>
                            <span class='message__avatar'>
                                <img :src="item.user.avatar || placeholderImg" alt="">
                            </span>
                            <p class='message__text'>{{item.content}}</p>
                        </div>
                    </slide>
                    <i class="iconfont icon-close-pure" @click='messageShow = false'></i>
                </div>

                <div class="slogen">
                    <p class="slogen__item"> <img src="../images/user_slogen3.png"> <span>51信用卡战略投资</span></p>
                    <p class="slogen__item"> <img src="../images/user_slogen2.png"> <span>资料安全</span></p>
                    <p class="slogen__item"> <img src="../images/user_slogen1.png"> <span>信息真实</span></p>
                </div>
                <div class="recommend-list-title">
                    <div class="index-item borrow" :class='{active:index == 0}' @click='index=0'>
                        <img class='avatar' src="../images/avatar_borrower@3x.png">
                        <p>TA们正在求借款</p>
                    </div>
                    <div class="index-item lend" :class='{active:index == 1}' @click='index=1'>
                        <img class='avatar' src="../images/avatar_lender@3x.png">
                        <p>TA们正在求借款</p>
                    </div>
                </div>
                <template>
                    <div class="recommend-toolbar" ref='scrollDom'>
                        <span class="recommend-toobar__total">{{borrowCount}}条记录</span>
                        <span v-show='!loading_switch' class="recommend-toolbar__switch" @click='switchRecommend("scroll")'>换一批</span>
                        <div v-show='loading_switch' class='recommend-filter-loading'><loading :size='12'></loading></div>
                    </div>
                    <div class="recommend-box" v-if='borrowList.length'>
                        <div class='recommend'>
                            <div class="recommend__item" v-for='item in borrowList' @click='goRecommend(item)'>
                                <div class='recommend__borrow-info'>
                                    <div class="recommend__borrow-top">
                                        <img class='recommend__avatar' :src="item.user.avatar || placeholderImg">
                                        <p class='zm'>{{item.zmScore || placeholder}}</p>
                                        <img v-if='item.isContact' width="16" height='16' src="../images/contactloan.png">
                                    </div>
                                    <div class="recommend__borrow-bottom">
                                        <p class='name'>{{item.user.realName || placeholder}}</p>
                                        <p class='money'>求借<span>{{item.borrowAmount | toYuanInt}}元</span></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="no-data" v-if='!borrowList.length && !loading_switch'>
                        <p>没有数据～</p>
                    </div>
                </template>
                <div v-show='loading_switch' class='button pure'><loading mode='full' :size='12'></loading></div>
                <p v-show='!loading_switch && !lastPage' class='recommend-swtich-button button pure purple' @click='switchRecommend'>加载更多</p>
                <p v-show='!loading_switch && lastPage' class='recommend-swtich-button button pure purple' @click='switchRecommend("scroll")'>点击查看下一页</p>

                <!-- <div class="placeholder" v-if='allEmpty && !loading'>
                    <img src="../images/loading_0.png" width="80" alt="">
                    <p>有借，有钱借</p>
                </div> -->

            </div>
        </div>

        <footer-bar></footer-bar>


        <modal
            class='modal-borrow'
            :show='show_modal_borrow'
            @close='show_modal_borrow=false'
            mode='bottom'>
            <div class="modal-borrow-box">
                <p class="modal-borrow__title">芝麻分</p>
                <ul class="modal-borrow__list">
                    <li class="modal-borrow__item"><span>580以下</span></li>
                    <li class="modal-borrow__item"><span>581～600</span></li>
                    <li class="modal-borrow__item"><span>601～650</span></li>
                    <li class="modal-borrow__item"><span>651以上</span></li>
                </ul>
                <p class="modal-borrow__title">借款金额</p>
                <ul class="modal-borrow__list">
                    <li class="modal-borrow__item"><span>1000以下</span></li>
                    <li class="modal-borrow__item"><span>1001～3000</span></li>
                    <li class="modal-borrow__item"><span>3001～10000</span></li>
                    <li class="modal-borrow__item"><span>10001以上</span></li>
                </ul>
                <p class="modal-borrow__title">设备类型</p>
                <ul class="modal-borrow__list">
                    <li class="modal-borrow__item"><span>iPhone 6</span></li>
                    <li class="modal-borrow__item"><span>iPhone 6P</span></li>
                    <li class="modal-borrow__item"><span>iPhone 6S</span></li>
                    <li class="modal-borrow__item"><span>iPhone 6SP</span></li>
                    <li class="modal-borrow__item"><span>iPhone 7</span></li>
                    <li class="modal-borrow__item"><span>iPhone 7P</span></li>
                    <li class="modal-borrow__item"><span>安卓</span></li>
                    <li class="modal-borrow__item"><span>其他</span></li>
                </ul>
            </div>
        </modal>

    </div>
</template>

<script>
    import { Promise } from 'es6-promise'
    import dynamics from 'dynamics.js'
    import footerBar from '../components/FooterBar.vue'
    import selectGroup from '../components/SelectGroup.vue'
    import selectOption from '../components/SelectOption.vue'
    import radioGroup from '../components/RadioGroup.vue'
    import areaSelect from '../components/AreaSelect.vue'
    import radio from '../components/Radio.vue'
    import loading from '../components/Loading.vue'
    import checkBox from '../components/CheckBox.vue'
    import toolTip from '../components/ToolTip.vue'
    import modal from '../components/Modal.vue'
    import confirm from '../components/Confirm.vue'
    import buttonLoading from '../components/ButtonLoading.vue'
    import pagination from '../components/Pagination.vue'
    import payPassword from '../components/PayPassword.vue'
    import pickerList from '../components/PickerList.vue'
    import countDown from '../components/CountDown.vue'
    import slide from '../components/Slide.vue'
    import toYuan from '../filters/filter-toYuan'
    import dateFormat from '../filters/filter-dateFormat'
    import { timeToHours } from '../filters/filter-timeFormat'
    import { convertRequestURL } from '../utils/utils'
    import  { mapGetters, mapActions }  from 'vuex'
    import { addLenderValidation, resetAccountPasswordValidation, operatorEditValidation } from '../validation/validation'
    import { contactApi, loanInApi, loanOutApi, messageApi } from '../api/api'
    import { scrollLoading, scrollLoadingOff } from '../utils/utils'
    import moment from 'moment'

    export default {
        components:{
            footerBar,
            selectGroup,
            selectOption,
            radioGroup,
            radio,
            checkBox,
            pickerList,
            areaSelect,
            loading,
            toolTip,
            modal,
            confirm,
            slide,
            buttonLoading,
            pagination,
            payPassword,
            countDown,
        },
        filters:{
            toYuan,
            dateFormat,
            timeToHours,
            diffDay(time){
                let now = moment()
                let day = moment(time)
                let diff = day - now
            },
            toYuanInt(money){
                if(money === 0) return '0'
                else if(!money) return '0'
                else if(money >= 1000000){
                    return Number((money/1000000).toFixed(2)) + '万'
                }
                else return Number((money/100).toFixed(2))
            }

        },
        data() {
            return {
                index:0,
                currentPage:'',
                borrowPage:'',
                totalPage:'',
                totalCount:'',
                recommend:[],
                loading_switch:false,
                zmxy:'',
                zmxyList:[{
                    value:'',
                    display:'按芝麻分筛选'
                },{
                    value:'650-10000',
                    display:'650以上'
                },{
                    value:'601-650',
                    display:'601~650'
                },{
                    value:'581-600',
                    display:'581~600'
                },{
                    value:'0-580',
                    display:'580以下'
                }],
                placeholderImg:require('../images/loading_1.png'),
                payPasswordShow:false,
                messageShow:true,
                messageList:[],
                messageIndex:0,
                main:{},
                payStatus:'',
                password:'',
                show_modal_borrow:false,
                placeholder:'--',
                userCount:'',
                info:{},
                records:[],
                num:1,
                loading:true,
                loading_count:false,
            }
        },
        computed:{
            ...mapGetters([
                'msgTip',
                'localInfo'
            ]),
            borrowList(){
                return this.localInfo.borrowList
            },
            borrowPageInfo(){
                return this.localInfo.borrowPageInfo
            },
            borrowCount(){
                if(this.localInfo.borrowPageInfo.outPageInfo)
                return this.localInfo.borrowPageInfo.outPageInfo.totalCount
            },
            borrowPages(){
                if(this.localInfo.borrowPageInfo.outPageInfo){
                    let total = this.localInfo.borrowPageInfo.outPageInfo.totalPage
                    let arr = [] 
                    _.times(total,(n)=>{
                        arr.push({
                            value:n+1,
                            display:`第${n+1}页`
                        })
                    })
                    return arr
                }
                return []
            },
            lastPage(){
                if(this.localInfo.borrowPageInfo.inPageInfo){
                    return this.localInfo.borrowPageInfo.inPageInfo.totalPage == this.localInfo.borrowPageInfo.inPageInfo.pageNum
                }
            },
            userInfo(){
                return this.localInfo.userInfo
            },
            needLogin(){
                return this.localInfo.needLogin
            },
        },
        methods:{
            // actions
            ...mapActions([
                'showLoading',
                'hideLoading',
                'setMsgTip',
                'borrowListSquare'
            ]),

            // filters
            timestampToDate(timestamp){
                if(!timestamp) return this.placeholder
                return moment(timestamp).format('YYYY-MM-DD')
            },

            // function

            
            daysTransform(from,to,type){
                let suffix
                let fromStr = from
                let toStr = to

                if(type == 'day'){
                    fromStr = fromStr+ '天'
                    toStr = toStr+ '天'
                }
                else{
                    fromStr = fromStr + '期'
                    toStr = toStr + '期'
                }

                if(from >= 30 && type == 'day'){
                    suffix = '个月'
                    fromStr = from / 30 + '个月'

                }
                if(to >= 30 && type == 'day'){
                    suffix = '个月'
                    toStr = to / 30 + '个月'

                }
                if(from == to){
                    return fromStr
                }
                else{
                    return fromStr  + '~' + toStr 
                }
            },
            goIdSelect(){
                this.$router.push({
                    name:'id-select'
                })
            },
            caclPersent(pass,reject){
                if(pass == 0) return 0
                return (pass/(pass+reject)*100).toFixed(2)
            },
            goDetailMe(item){
                let number = item.lendNo
                let isMyPublishLend = item.isMyPublishLend
                let isMyPublishLendStr

                if(item.isMyPublishLend === false){
                    isMyPublishLendStr = 'false'
                }
                else{
                    isMyPublishLendStr = 'true'
                }

                this.$router.push({
                    name:'loan-out-detail-me',
                    params:{
                        number:number
                    },
                    query:{
                        isMyPublishLend:isMyPublishLendStr
                    }
                })
            },
            goMessageDetail(event){
                let el = $(event.target).closest('.swiper-slide')
                if(!el.length) return

                let id = el.data('id')
            
                this.$router.push({
                    name:'message-box-detail',
                    params:{
                        id:id
                    }
                })
            },
            goRouter(name){
                if(!this.checkLogin()) return

                this.$router.push({
                    name:name
                })
            },
            goLoanOutWant(){
                if(!this.check()) return
                
                this.$router.push({
                    name:'loan-out-want-index'
                })
            },
            goLoanOutRecord(){
                if(!this.checkLogin()) return

                this.$router.push({
                    name:'loan-out-record'
                })
            },
            checkLogin(){
                if(this.needLogin){
                    this.$router.push({
                        name:'bind-phone'
                    })
                    return false
                }
                if(this.userInfo.user){
                    if(!this.userInfo.user.bizRole){
                        this.$router.push({
                            name:'id-select'
                        })
                        return false
                    }
                }
                return true
            },
            check(){
                if(this.needLogin){
                    this.$router.push({
                        name:'bind-phone'
                    })
                    return false
                }
                return true

            },
            getMain(num){
                // this.showLoading()
                loanOutApi.main()
                .then(result=>{
                    // this.hideLoading()
                    this.main = result
                })
                .catch(error => {
                    console.error(error)
                    // this.hideLoading()
                })
            },
            goChat(id){
                if(!this.userInfo.isPay || this.userInfo.isExpired){
                    this.setMsgTip({
                        text:'请先完成信用报告',
                        type:'info'

                    })
                    return
                }
                
                this.showLoading()
                contactApi.im({
                    uuid:id
                })
                .then(result=>{
                    let info = result.info
                    let myAccid = info.myAccid
                    let accid = info.accid
                    let token = info.token
                    location.href = convertRequestURL(`?token=${token}&uid=${myAccid}#/session`,'chat')
                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            getInfo(){
                this.loading = true
                loanOutApi.myPublishLending()
                .then(result=>{
                    this.loading = false
                    this.info = result
                })
                .catch(error => {
                    console.error(error)
                    this.loading = false
                })
            },
            getMessage(){
                messageApi.unReadList()
                .then(result=>{
                    this.messageList = result
                })
                .catch(error => {
                    console.error(error)
                })
            },
            goRecommend(item){
                if(!this.checkLogin()) return
                    
                this.$ga.event({
                  eventCategory: 'link',
                  eventAction: 'click',
                  eventLabel: 'borrowRecommend - ' + this.channel + '-' + item.user.realName
                })

                let user = item.user
                let borrow = item.borrow
                if(!borrow){
                    this.$router.push({
                        name:'contact-detail',
                        params:{
                            id:user.uuid,
                        },
                        query:{
                            type:'add'
                        }
                    })
                }
                else{
                    this.$router.push({
                        name:'loan-in-detail-other',
                        params:{
                            number:borrow.borrowNo
                        },
                        query:{
                            type:'add'
                        }
                    })
                }
            },
            apiRecommend(){
                this.loading_switch = true
                this.borrowListSquare({
                    refresh:true,
                    zmxy:this.zmxy,
                    pageNum:this.currentPage
                })
                .then(result=>{
                    this.loading_switch = false
                    this.setCurrentPage()
                })
                .catch(error => {
                    console.error(error)
                    this.loading_switch = false
                })
            },
            getRecommend(num){
                console.log(this.borrowList.length)
                if(!this.borrowList.length){
                    let outPageInfo = this.borrowPageInfo.outPageInfo
                    let outGetNum 
                    if(outPageInfo){
                        if(outPageInfo.totalPage == outPageInfo.pageNum){
                            outGetNum = 1
                        }
                        else{
                            outGetNum = outPageInfo.pageNum + 1
                        }
                    }
                    this.loading_switch = true
                    this.borrowListSquare({
                        refresh:false,
                        zmxy:this.zmxy,
                        pageNum:outGetNum
                    })
                    .then(result=>{
                        console.log(this.loading_switch)
                        this.loading_switch = false
                        this.setCurrentPage()
                    })
                    .catch(error => {
                        console.error(error)
                        this.loading_switch = false
                    })
                }
                else{
                    this.setCurrentPage()
                }
            },
            setCurrentPage(){
                if(this.localInfo.borrowPageInfo.outPageInfo){
                    this.currentPage =  this.localInfo.borrowPageInfo.outPageInfo.pageNum
                }
            },
            switchRecommend(type,refresh){
                if(this.loading_switch == true) return
                this.loading_switch = true
                let scrollTop = $(this.$refs.content).scrollTop()
                let top = scrollTop + $(this.$refs.scrollDom).offset().top

                this.borrowListSquare({
                    refresh:refresh,
                    zmxy:this.zmxy
                })
                .then(result=>{
                    this.setCurrentPage()
                    if(type == 'scroll'){
                        let o = {
                          scroll: scrollTop
                        }

                        // $('body').css('visibility','hidden')

                        dynamics.animate(o, {
                          scroll: top,
                        }, {
                          change: ()=> {
                            $(this.$refs.content).scrollTop(o.scroll);
                          },
                          complete:()=>{
                            setTimeout(()=>{
                                this.loading_switch = false
                            },200)
                          },
                          type: dynamics.easeInOut,
                          duration: 500,
                          friction: 50
                        })
                    }
                    else{
                        this.loading_switch = false
                    }
                })
                .catch(error => {
                    console.error(error)
                    this.loading_switch = false
                })
            }
        },
        created(){
            this.getMain()
            this.getInfo()
            this.getMessage()
            this.getRecommend(1)
            this.$nextTick(()=>{
                scrollLoading('.loan-out-index-wrapper','.loan-out-index-box',()=>{
                    console.log('scroll')
                    if(this.loading_switch) return
                    if(this.lastPage) return
                    this.switchRecommend()
                },20)
            })
        },
        destroyed(){
            scrollLoadingOff('.loan-out-index')
        }
    }
</script>

<style lang="scss">
    @import "../sass/variables";
    @import "../sass/extends";
    @import "../sass/mixins";
    .loan-index{
        .recommend-toolbar__switch{
            @extend %font-button;
            line-height:48px;
            color:$orange;
            padding:0 16px;
        }
        .recommend-toolbar{
            margin-top: 16px;
        }
        .recommend-list-title{
            padding: 0;
            display: flex;
            .index-item{
                padding:15px 16px;
                border-bottom: 2px solid transparent;
                flex:1;
                display: flex;
                align-items: center;
                img{
                    width: 24px;
                    height: 24px;
                }
                p{
                    @extend %font-body2;
                }
                &.borrow.active,&.borrow:active{
                    p{
                        color:$orange;
                    }
                    border-color:$orange;
                }
                &.lend.active,&.lend:active{
                    p{
                        color:$purple;
                    }
                    border-color:$purple;
                }
            }
        }
        .slogen{
            margin-top: 0;
        }
        .loan-out-index-box{
            transition:height ease .3s;
        }
        .recommend__borrow-info{
            flex:1;
            padding: 0 16px;
        }
        .recommend__borrow-top{
            @extend %font-caption;
            display: flex;
            align-items: center;
            .name{
                @extend %font-caption;
                color:$importColor;
            }
            .zm{
                display: block;
                width: 49px;
                height: 21px;
                line-height: 21px;
                background: url(../images/bg_zhimafen@3x.png) no-repeat left center;
                background-size: 49px 21px;
                margin-left:9px;
                text-align:left;
                padding-left:18px;
                color:$green;
            }
        }
        .recommend__borrow-bottom{
            display: flex;
            justify-content: space-between;
            align-items: center;;
            text-align:left;
            @extend %font-caption;
            color:$defaultColor;
            .name{
                color:$importColor;
            }
            .money span{
                @extend %font-body2;
                color:$importColor;
            }
        }
        .loan-out-card{
            margin-top: 16px;
        }
        .want-loan__text{
            @extend %font-caption;
            padding-top: 6px;
            text-align: center;
        }
        .want-loan__record{
            padding-top: 12px;
            .button{
                color:$purple;
            }
        }
        .component-picker-list{
            width: auto;
            position: relative;
            overflow:hidden;
            &:before{
                @include triangle(10px,$defaultColor,bottom)
                content:'';
                position: absolute;
                top:50%;
                margin-top:-2.5px;
                right:0;
            }
        }
        .recommend-filter-loading{
            width: 50px;
            height: 48px;
        }
        .modal-borrow{
            z-index:$zIndex_top;
        }
        .modal-borrow__title{
            @extend %font-body2;
            padding:16px 4px 8px 4px;
            color:$importColor;
        }
        .modal-borrow__list{
            overflow:hidden;
        }
        .modal-borrow__item{
            width:(100%/3);
            float:left;
            @extend %font-body1;
            text-align: center;
            padding:4px;
            box-sizing:border-box;
            border-radius:2px;
            span{
                display: block;
                background-color: $backgroundColor;
                padding: 6.5px 0;
                &.active,&:active{
                    color:$orange;
                    background-color: #FFCCBC;
                }
            }
        }
    }

</style>
